// 
//  Copyright 2011  comphilip
// 
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
// 
//        http://www.apache.org/licenses/LICENSE-2.0
// 
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;
using Dict4Engkoo.Command;

namespace Dict4Engkoo.Processor {
	/// <summary>
	/// Processor factory to create IDictProcessor
	/// </summary>
	public static class ProcessorFactory {
		private const string RESID = "CommandMap.xml";
		
		/// <summary>Creates <see cref="IDictProcessor"/> instance with default command setting.</summary>
		/// <returns>A <see cref="IDictProcessor"/></returns>
		public static IDictProcessor CreateProcessor(){
			return new CommandDictProcessor(CreateCommandMap(), CreateStartCommand());
		}
		
		private static ICommand CreateStartCommand(){
			using(StreamReader reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(RESID))){
				XDocument doc = XDocument.Load(reader);
				return Activator.CreateInstance(Type.GetType(doc.Root.Element("startCommand").Attribute("type").Value)) as ICommand;
			}
		}
		
		private static IDictionary<string, ConstructorInfo> CreateCommandMap(){
			using(StreamReader reader= new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(RESID))){
				XDocument doc = XDocument.Load(reader);
				return (from x in doc.Root.Elements("command") select x).ToDictionary(
				                                                                                   x=>x.Attribute("name").Value,
				                                                                                   x=>Type.GetType(x.Attribute("type").Value).GetConstructor(new Type[0]),
				                                                                                   StringComparer.OrdinalIgnoreCase);
			}
		}
	}
}

